package com.blue.spring.redis;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

/**
 * RedisHttpSesstion 的 Filter 实现，必须放在 Filter链的第一个
 * 
 * @author zhengj
 * @since 2016年5月17日 1.0
 */
public class RedisHttpSessionFilter implements Filter
{
	private static Logger logger = LoggerFactory.getLogger(RedisHttpSessionFilter.class);
	
	private RedisTemplate<String, Object> redisTemplate;
	
	private String tokenName = "token";
	private int expire = 3600;
	private String key = "com_blue:redis_session:";
	
	public RedisHttpSessionFilter()
	{
	}

	@Override
	public void destroy()
	{
		
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException
	{
		HttpServletRequest req = (HttpServletRequest)request;
		HttpServletResponse resp = (HttpServletResponse)response;
		
		this.init(req);
		
		RedisHttpServletRequestWrapper requestWrapper = new RedisHttpServletRequestWrapper(req, resp, redisTemplate, tokenName, expire, key);
		
		chain.doFilter(requestWrapper, resp);
	}
	
	@SuppressWarnings("unchecked")
	private void init(HttpServletRequest request)
	{
		if (redisTemplate != null)
			return;
		
		WebApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(request.getServletContext());
		redisTemplate = ctx.getBean("redisTemplate", RedisTemplate.class);
	}

	@Override
	public void init(FilterConfig config) throws ServletException
	{
		String tokenName = config.getInitParameter("tokenName");
		if (tokenName != null && !tokenName.isEmpty())
			this.tokenName = tokenName;
		
		String key = config.getInitParameter("key");
		if (key != null && !key.isEmpty())
			this.key = key;
		
		String expire = config.getInitParameter("expire");
		if (expire != null && !expire.isEmpty())
		{
			try
			{
				this.expire = Integer.parseInt(expire);
			}
			catch (NumberFormatException e)
			{
				logger.warn("HttpSession 过期时间格式错误", expire);
			}
		}
	}
	
}
